package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.xs.XsOrder;
import com.ruoyi.system.domain.xs.XsOrderTb;
import com.ruoyi.system.domain.xs.XsStore;
import com.ruoyi.system.mapper.XsOrderMapper;
import com.ruoyi.system.mapper.XsStoreMapper;
import com.ruoyi.system.service.IXsOrderTbService;
import com.ruoyi.system.service.IXsStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 写稿店铺Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-13
 */
@Service
public class XsStoreServiceImpl extends ServiceImpl<XsStoreMapper, XsStore>
        implements IXsStoreService {

    @Autowired
    private XsStoreMapper xsStoreMapper;

    /** 订单表 */
    @Autowired
    private XsOrderMapper xsOrderMapper;

    /** 淘宝订单表 */
    @Autowired
    private IXsOrderTbService xsOrderTbService;

    /**
     * 查询写稿店铺
     *
     * @param id 写稿店铺主键
     * @return 写稿店铺
     */
    @Override
    public XsStore selectXsStoreById(Long id) {
        return xsStoreMapper.selectXsStoreById(id);
    }

    /**
     * 查询写稿店铺列表
     *
     * @param xsStore 写稿店铺
     * @return 写稿店铺
     */
    @Override
    public List<XsStore> selectXsStoreList(XsStore xsStore) {
        return xsStoreMapper.selectXsStoreList(xsStore);
    }

    /**
     * 新增写稿店铺
     *
     * @param xsStore 写稿店铺
     * @return 结果
     */
    @Override
    public int insertXsStore(XsStore xsStore) {
        xsStore.setCreateTime(DateUtils.getNowDate());
        xsStore.setCreateBy(SecurityUtils.getUsername());
        if (StringUtils.isEmpty(xsStore.getStoreCode())) {
            // 店铺编号如果为空 设置店铺编号
            String result = PinyinUtil.getFirstLetter(xsStore.getStoreName(), "");
            xsStore.setStoreCode(result);
        }
        XsStore store = this.lambdaQuery().eq(XsStore::getStoreCode, xsStore.getStoreCode()).last("limit 1").one();
        if (ObjectUtil.isNotEmpty(store)) {
            throw new GlobalException("新增失败，店铺编号已存在，请更换编号");
        }
        return xsStoreMapper.insertXsStore(xsStore);
    }

    /**
     * 修改写稿店铺
     *
     * @param xsStore 写稿店铺
     * @return 结果
     */
    @Override
    public int updateXsStore(XsStore xsStore) {
        XsStore store = xsStoreMapper.selectById(xsStore.getId());
        if (ObjectUtil.isEmpty(store)) {
            throw new GlobalException("店铺异常");
        }
        if (!store.getStoreCode().equals(xsStore.getStoreCode())) {
            LambdaQueryWrapper<XsOrder> lqw = new LambdaQueryWrapper<>();
            lqw.eq(XsOrder::getStoreCode, store.getStoreCode()).last("limit 1");
            XsOrder order = xsOrderMapper.selectOne(lqw);
            XsOrderTb tb = xsOrderTbService.lambdaQuery().eq(XsOrderTb::getStoreCode, store.getStoreCode()).last("limit 1").one();
            if (ObjectUtil.isNotEmpty(order) || ObjectUtil.isNotEmpty(tb)) {
                throw new GlobalException("原编号已应用，不支持修改");
            }
        }
        xsStore.setUpdateTime(DateUtils.getNowDate());
        xsStore.setUpdateBy(SecurityUtils.getUsername());
        if (StringUtils.isEmpty(xsStore.getStoreCode())) {
            // 店铺编号如果为空 设置店铺编号
            String result = PinyinUtil.getFirstLetter(xsStore.getStoreName(), "");
            xsStore.setStoreCode(result);
        }
        XsStore s = this.lambdaQuery().eq(XsStore::getStoreCode, xsStore.getStoreCode()).last("limit 1").one();
        if (ObjectUtil.isNotEmpty(s) && !s.getId().equals(store.getId())) {
            throw new GlobalException("修改失败，店铺编号已存在，请更换编号");
        }
        return xsStoreMapper.updateXsStore(xsStore);
    }

    /**
     * 批量删除写稿店铺
     *
     * @param ids 需要删除的写稿店铺主键
     * @return 结果
     */
    @Override
    public int deleteXsStoreByIds(Long[] ids) {
        List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
        List<XsStore> storeList = this.lambdaQuery().in(XsStore::getId, idList).list();
        if (CollectionUtil.isEmpty(storeList)) {
            throw new GlobalException("店铺信息异常");
        }
        Set<String> codeSet = storeList.stream().map(XsStore::getStoreCode).filter(Objects::nonNull).collect(Collectors.toSet());
        // 判断店铺是否使用 已使用不可删除
        LambdaQueryWrapper<XsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.in(XsOrder::getStoreCode, codeSet);
        List<XsOrder> orderList = xsOrderMapper.selectList(lqw);
        if (CollectionUtil.isNotEmpty(orderList)) {
            throw new GlobalException("无法删除，该店铺已应用");
        }
        List<XsOrderTb> tbList = xsOrderTbService.lambdaQuery().in(XsOrderTb::getStoreCode, codeSet).groupBy(XsOrderTb::getStoreCode).list();
        if (CollectionUtil.isNotEmpty(tbList)) {
            throw new GlobalException("无法删除，该店铺已应用");
        }
        return xsStoreMapper.deleteXsStoreByIds(ids);
    }

    /**
     * 删除写稿店铺信息
     *
     * @param id 写稿店铺主键
     * @return 结果
     */
    @Override
    public int deleteXsStoreById(Long id) {
        return xsStoreMapper.deleteXsStoreById(id);
    }
}
